﻿using Microsoft.Extensions.Logging;
using System;
using System.Reflection;
using System.Linq;
namespace Athena.Correlation.Implementations
{
    using CorrelationAttributes;
    public class ServiceCorrelationIdGenerator : IServiceCorrelationIdGenerator
    {

        private readonly ILogger _logger;

        public ServiceCorrelationIdGenerator(ILogger<ServiceCorrelationIdGenerator> logger)
        {
            _logger = logger;
        }

        public string GenerateCorrelationId(MethodInfo method)
        {
            var correlationName = method.DeclaringType.GetCustomAttribute<CorrelationHeaderAttribute>()?.HeaderName;

            correlationName = string.IsNullOrWhiteSpace(correlationName) ? method.DeclaringType.FullName : correlationName;

            var correlationBody = method.GetCustomAttribute<CorrelationBodyAttribute>()?.BodyName;

            if (string.IsNullOrWhiteSpace(correlationBody))
            {
                var correlationid = $"{correlationName}.{method.Name}";
                var parameters = method.GetParameters();
                if (parameters.Any())
                {
                    correlationid += "_" + string.Join("_", parameters.Select(x => x.Name));
                }
                return correlationid;
            }
            else
            {
                return $"{correlationName}.{correlationBody}";
            }
        }
    }
}
